import * as types from '../actionTypes/todos';

const initialState = [
  { id: 1, text: '吃饭', done: true },
  { id: 2, text: '学习', done: false },
  { id: 3, text: '睡觉', done: false },
];

export const todos = (state = initialState, action) => {
  console.log('reducer 中 收到的 action', action);
  // 处理删除todo
  if (action.type === types.DEL_TODO) {
    return state.filter((item) => item.id !== action.payload);
  }
  // 处理任务完成状态
  if (action.type === types.TOGGLE_TODO) {
    const newState = state.map((item) => {
      if (item.id === action.payload) {
        return {
          ...item,
          done: !item.done,
        };
        // 不能这样写，不符合redux处理数据的规范（数据不可变，每次修改都要返回新的数据）
        // return item.done = !item.done
      } else {
        return item;
      }
    });
    return newState;
  }
  // 添加任务
  if (action.type === types.ADD_TODO) {
    const newState = [
      ...state,
      {
        id: Date.now(),
        text: action.payload,
        done: false,
      },
    ];
    return newState;
  }
  // 全选/反选
  if (action.type === types.TOGGLE_ALL) {
    const newState = state.map((item) => {
      return {
        ...item,
        done: action.payload,
      };
    });
    // return state.map((item) => ({ ...item, done: action.payload }));
    return newState;
  }
  // 清除完成的todo
  if (action.type === types.CLEAR_DONE) {
    return state.filter((item) => !item.done);
  }
  // 更新todo
  if (action.type === types.UPDATE_TODO) {
    return state.map((item) => {
      if (item.id === action.payload.id) {
        return {
          ...item,
          text: action.payload.text,
        };
      } else {
        return item;
      }
    });
  }

  return state;
};
